package com.free.bsf.core.filter;

import com.free.bsf.core.util.WebUtils;
import lombok.val;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Classname WebContextInterceptor
 * @Description web上下文拦截器
 * @Date 2021/4/9 12:16
 * @Created by chejiangyi
 */
public class WebContextInterceptor implements HandlerInterceptor {
    public WebContextInterceptor() { }
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        if(WebUtils.getContext()!=null&&o!=null&&o instanceof HandlerMethod){
            val handler = (HandlerMethod)o;
            WebUtils.getContext().setMethod(handler.getMethod());
            WebUtils.getContext().setController(handler.getBean());
        }
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        if(WebUtils.getContext()!=null&&o!=null&&o instanceof HandlerMethod){
            WebUtils.getContext().setMethod(null);
            WebUtils.getContext().setController(null);
        }
    }
}
